package org.example.attendancesystem.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.example.attendancesystem.domain.AttendanceRecords;
import org.example.attendancesystem.domain.Result;
import org.example.attendancesystem.domain.SessionParams;
import org.example.attendancesystem.domain.vo.AttendanceRecordWithTitleVO;
import org.example.attendancesystem.mapper.AttendanceRecordsMapper;
import org.example.attendancesystem.service.AttendanceRecordsService;
import org.example.attendancesystem.service.SessionParamsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

import static org.example.attendancesystem.utils.tool.getDistance;
import static org.example.attendancesystem.utils.tool.getVincentyDistance;

@CrossOrigin
@RestController
@RequestMapping("/signInRecord")
public class SignRecordController {
    @Autowired
    private AttendanceRecordsMapper attendanceRecordsMapper;
    @Autowired
    private AttendanceRecordsService attendanceRecordsService;
    @Autowired
    private SessionParamsService sessionParamsService;

    @GetMapping("/queryLocationCheckInDataRe")
    public Result<List<AttendanceRecordWithTitleVO>> queryLocationCheckInDataRe(@RequestParam("studentId") Long studentId){
        List<AttendanceRecordWithTitleVO> list = attendanceRecordsMapper.selectLocationRecordsWithTitleByStudentId(studentId.toString());
        return Result.success(list);

    }

    @PostMapping("/updateLocationStatus")
    public Result<String> updateLocationStatus(@RequestBody AttendanceRecordWithTitleVO attendanceRecord,@RequestParam("latitude") String latitude,@RequestParam("longitude") String longitude){
        double userLat = Double.parseDouble(latitude);
        double userLng = Double.parseDouble(longitude);

//        System.out.println(latitude);
//        System.out.println(longitude);


        SessionParams sessionParams = sessionParamsService.getById(attendanceRecord.getSessionId());

        // 目标签到地点的经纬度（例如：学校）
        BigDecimal targetLat = sessionParams.getLatitude();
        BigDecimal targetLng = sessionParams.getLongitude();

        // 计算距离
        double distance = getVincentyDistance(userLat, userLng, targetLat.doubleValue(), targetLng.doubleValue());
//        System.out.println(sessionParams.toString());
        System.out.println("用户与目标点距离：" + distance + " 米");

        if (distance<=10000){
            LambdaUpdateWrapper<AttendanceRecords> updateWrapper = new LambdaUpdateWrapper<AttendanceRecords>()
                    .eq(AttendanceRecords::getRecordId, attendanceRecord.getRecordId())
                    .set(AttendanceRecords::getStatus,"已签到");
            attendanceRecordsService.update(updateWrapper);
        }else {
            return Result.fail("不在签到范围内");
        }
        return Result.success("签到成功");
    }





}
